// 更新群组
import {User} from "~/server/models/user";

export default defineEventHandler(async (event) => {
    try {
        const method = event.node.req.method;

        if (method !== 'PUT' && method !== 'PATCH') {
            const errorMessage = `不支持的方法: ${method}`;
            console.error(errorMessage);
            throw new Error(errorMessage); // 抛出错误，因为这不是预期的PUT或PATCH请求
        }

        const body = await readBody(event);

        if (!body._id) {
            throw new Error("缺少_id");
        }
        const id = body._id;
        // 确保有数据被提供用于更新，实际应用中可能需要更详细的验证逻辑
        if (Object.keys(body).length === 0) {
            throw new Error("更新内容不能为空");
        }

        const updatedGroup = await User.updateOne({_id: id}, body);
        if (!updatedGroup) {
            throw new Error("更新失败，未找到");
        }

        return {message: "更新成功"};
    } catch (error) {
        console.error("操作过程中发生错误:", error);
        return {
            error: "操作过程中发生错误",
            details: error instanceof Error ? error.message : "未知错误",
        };
    }
});
